package com.wskh.msmService.controller;

import com.wskh.commonUtil.R;
import com.wskh.commonUtil.RandomUtil;
import com.wskh.msmService.service.MsmService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(value="阿里云短信服务")
@RestController
@RequestMapping("/msmService/msm")
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE}) // 允许请求跨域
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "发送手机验证码")
    @GetMapping(value = "/sendPhone/{phone}")
    @Async
    public R sendPhone(@PathVariable String phone) {

        String code = redisTemplate.opsForValue().get(phone);

        if(!StringUtils.isEmpty(code)){
            System.out.println("code = " + code);
            return R.ok();
        }

        // 生成6位随机数
        code = RandomUtil.getSixBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code", code);
        System.out.println("code = " + code);

        // 模版CODE: SMS_226520220
        boolean isSend = msmService.sendPhone(phone, "SMS_226520220", param);

        if(isSend) {
            // 存入redis 5分钟内有效
            redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("发送短信失败");
        }

    }

    @ApiOperation(value = "发送邮箱验证码")
    @GetMapping(value = "/sendEmail/{email}")
    @Async
    public R sendEmail(@PathVariable String email) {

        String code = redisTemplate.opsForValue().get(email);

        if(!StringUtils.isEmpty(code)){
            System.out.println("code = " + code);
            return R.ok();
        }

        // 生成6位随机数
        code = RandomUtil.getSixBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code", code);
        System.out.println("code = " + code);

        // 模版CODE: SMS_226520220
        boolean isSend = msmService.sendEmail(email,code);

        if(isSend) {
            // 存入redis 5分钟内有效
            redisTemplate.opsForValue().set(email, code,5, TimeUnit.MINUTES);
            System.out.println("成功发送给"+email);
            return R.ok();
        } else {
            return R.error().message("发送短信失败");
        }

    }

}
